package com.stone.EasyTeaching.utilities;

import android.text.TextUtils;
import android.widget.EditText;
import org.apache.commons.lang.exception.NestableRuntimeException;
import org.apache.commons.lang.text.StrBuilder;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {
	public static boolean isBlank(String value) {
		return TextUtils.isEmpty(value);
	}

	public static boolean isEmpty(CharSequence value) {
		return TextUtils.isEmpty(value);
	}
    public static boolean isEmptyString(String strTarget){
        return ((null == strTarget) || (0 == strTarget.length()));
    }

	public static boolean isEmpty(EditText editText) {
		return TextUtils.isEmpty(editText.getText().toString().trim());
	}

	public static boolean parseArrayInt(int[] array, String value, String split) {
		if (array == null || StringUtils.isEmpty(value))
			return false;

		boolean ret = false;
		String[] ss = value.split(split);
		for (int i = 0; i < array.length && i < ss.length; i++) {
			ret = true;
			array[i] = Integer.parseInt(ss[i]);
		}

		return ret;
	}




	public static boolean isEqual(String compa, String compb) {
		if (compa == null || compb == null)
			return false;

		return compa.equals(compb);
	}

	// 去除字符串尾部空格
	public static String trimEnd(String str) {
		return str.replaceAll("[\\s]*$", "");
	}

	// 将字符串中所有的非标准字符（双字节字符）替换成两个标准字符（**，或其他的也可以）
	public static String convert(String str) {
		return str.replaceAll("[^\\x00-\\xff]", "**");
	}

	public static String getUTF8Dom() {
		byte[] buffer = new byte[3];
		buffer[0] = (byte) 0xEF;
		buffer[1] = (byte) 0xBB;
		buffer[2] = (byte) 0xBF;

		try {
			return new String(buffer, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return "";
	}

	public static boolean parseArrayString(String[] array, String value,
			String split) {
		if (array == null || StringUtils.isEmpty(value))
			return false;

		boolean ret = false;
		String[] ss = value.split(split);
		for (int i = 0; i < array.length && i < ss.length; i++) {
			ret = true;
			array[i] = ss[i];
		}

		return ret;
	}

	public static boolean copyString(String[] src, String[] dest) {
		if (src == null || dest == null)
			return false;

		for (int i = 0; i < dest.length; i++) {
			dest[i] = "";
		}

		for (int i = 0; i < dest.length && i < src.length; i++) {
			dest[i] = src[i];
		}

		return true;
	}

	public static String getUrlName(String url) {
		if (StringUtils.isEmpty(url))
			return "";

		int index = url.indexOf("?");
		if (index > 0)
			url = url.substring(0, index);

		index = url.lastIndexOf("/");
		if (index < 0)
			index = url.indexOf("\\");

		if (index < 0)
			return url;

		return url.substring(index + 1);
	}

	public static String getTime(int tm) {
		int h = tm / 3600;
		int m = tm / 60;
		int s = tm % 60;

		if (h > 0)
			return String.format("%02d:%02d:%02d", h, m, s);

		else if (m > 0)
			return String.format("%02d:%02d", m, s);

		return String.format("%02d", s);
	}

	public static double parseDouble(String value, double default_value) {
		try {
			return Double.parseDouble(value);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return default_value;
	}

	public static int parseInt(String value, int default_value) {
		try {
			return Integer.parseInt(value);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return default_value;
	}

	public static String subString(String src, String find, int second) {
		int index = -find.length(), n = 0;
		do {
			int end = src.indexOf(find, index + find.length());
			if (end < 0)
				break;

			n++;
			index = end;
			if (n == second)
				return src.substring(0, index);

		} while (index > 0 && n < second);

		return src;
	}

	public static String delString(String src, String db, String de) {
		int index = -db.length();
		do {
			index = src.indexOf(db, index + db.length());
			if (index > 0) {
				int end = src.indexOf(de, index + de.length());
				if (end > 0)
					src = src.substring(0, index)
							+ src.substring(end + de.length());
				else
					src = src.substring(0, index);
			}
		} while (index > 0);

		return src;
	}

	public static int parseInt(String value) {
		if (isEmpty(value))
			return 0;

		try {
			return Integer.parseInt(value);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return 0;
	}

	public static long parseLong(String value, long default_value) {
		try {
			return Long.parseLong(value);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return default_value;
	}

	public static boolean isASCII(String str) {
		if (isEmpty(str))
			return false;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) >= 128 || str.charAt(i) < 0) {
				return false;
			}
		}
		return true;
	}

	public static final int MIN_LEN = 4;

	public static String delUTF8Dom(StringBuffer xml) {
		int len = xml.length() > MIN_LEN ? MIN_LEN : xml.length();
		String tmp = xml.substring(0, len);
		int index = tmp.indexOf('<');

		if (index < 0)
			index = tmp.indexOf('{');

		if (index < 0)
			index = tmp.indexOf('[');

		if (index > 0) {
			for (int i = 0; i < index; i++) {
				xml.setCharAt(i, ' ');
			}
		}

		return xml.toString();
	}

	public static boolean isContainsChinese(String str) {
		String regEx = "[\u4e00-\u9fa5]";
		Pattern pat = Pattern.compile(regEx);
		Matcher matcher = pat.matcher(str);
		boolean flg = false;
		if (matcher.find()) {
			flg = true;
		}
		return flg;
	}
	
	public static String join(List<String> array, String separator) {
        if (array == null) {
            return null;
        }
        int arraySize = array.size();
        int bufSize = (arraySize == 0 ? 0 : ((array.get(0) == null ? 16 : array.get(0).toString().length()) + 1) * arraySize);
        StringBuffer buf = new StringBuffer(bufSize);

        for (int i = 0; i < arraySize; i++) {
            if (i > 0) {
                buf.append(separator);
            }
            if (array.get(i) != null) {
                buf.append(array.get(i));
            }
        }
        return buf.toString();
    }

	//"([\\w\\u4E00-\\u9FA5]|[~!@#$%^&*()_+<>?:,./;'，。、‘：“《》？~！@#￥%……（）])+"
	//private final String reg ="^([a-z]|[A-Z]|[0-9]|[\u2E80-\u9FFF]){3,}|@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?|[wap.]{4}|[www.]{4}|[blog.]{5}|[bbs.]{4}|[.com]{4}|[.cn]{3}|[.net]{4}|[.org]{4}|[http://]{7}|[ftp://]{6}$";
	//@#&=*+-_.,:!?()/~'%
	public static String urlEncode(String url)
	{


		try {
			url = url.replaceAll("%",URLEncoder.encode("%", "utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Matcher matcher = Pattern.compile("([^\\x00-\\xff])+").matcher(url);

		while(matcher.find())
		{
			String tmp = matcher.group();
			try
			{
				url = url.replaceAll(tmp, URLEncoder.encode(tmp, "utf-8"));
			}
			catch (UnsupportedEncodingException e)
			{
				e.printStackTrace();
			}
		}

		return url ;
	}

    public static String decode(String unicodeStr) {
        if (unicodeStr == null) {
            return null;
        }
        StringBuffer retBuf = new StringBuffer();
        int maxLoop = unicodeStr.length();
        for (int i = 0; i < maxLoop; i++) {
            if (unicodeStr.charAt(i) == '\\') {
                if ((i < maxLoop - 5)
                        && ((unicodeStr.charAt(i + 1) == 'u') || (unicodeStr
                        .charAt(i + 1) == 'U')))
                    try {
                        retBuf.append((char) Integer.parseInt(
                                unicodeStr.substring(i + 2, i + 6), 16));
                        i += 5;
                    } catch (NumberFormatException localNumberFormatException) {
                        retBuf.append(unicodeStr.charAt(i));
                    }
                else
                    retBuf.append(unicodeStr.charAt(i));
            } else {
                retBuf.append(unicodeStr.charAt(i));
            }
        }
        return retBuf.toString();
    }

    public static void unescapeJava(Writer out, String str) throws IOException {
        if(out == null) {
            throw new IllegalArgumentException("The Writer must not be null");
        } else if(str != null) {
            int sz = str.length();
            StrBuilder unicode = new StrBuilder(4);
            boolean hadSlash = false;
            boolean inUnicode = false;

            for(int i = 0; i < sz; ++i) {
                char ch = str.charAt(i);
                if(inUnicode) {
                    unicode.append(ch);
                    if(unicode.length() == 4) {
                        try {
                            int nfe = Integer.parseInt(unicode.toString(), 16);
                            out.write((char)nfe);
                            unicode.setLength(0);
                            inUnicode = false;
                            hadSlash = false;
                        } catch (NumberFormatException var9) {
                            throw new NestableRuntimeException("Unable to parse unicode value: " + unicode, var9);
                        }
                    }
                } else if(hadSlash) {
                    hadSlash = false;
                    switch(ch) {
                        case '\"':
                            out.write(34);
                            break;
                        case '\'':
                            out.write(39);
                            break;
                        case '\\':
                            out.write(92);
                            break;
                        case 'b':
                            out.write(8);
                            break;
                        case 'f':
                            out.write(12);
                            break;
                        case 'n':
                            out.write(10);
                            break;
                        case 'r':
                            out.write(13);
                            break;
                        case 't':
                            out.write(9);
                            break;
                        case 'u':
                            inUnicode = true;
                            break;
                        default:
                            out.write(ch);
                    }
                } else if(ch == 92) {
                    hadSlash = true;
                } else {
                    out.write(ch);
                }
            }

            if(hadSlash) {
                out.write(92);
            }

        }
    }


}
